package jnpf.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import jnpf.common.exception.RagFlowException;
import jnpf.entity.*;
import jnpf.mapper.KnowMangeMapper;
import jnpf.model.ragFlow.common.RagFlowApiResult;
import jnpf.model.ragFlow.know.CreateKnowReq;
import jnpf.model.ragFlow.know.DatasetResp;
import jnpf.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jnpf.model.knowmange.*;

import java.math.BigDecimal;

import cn.hutool.core.util.ObjectUtil;
import jnpf.permission.model.authorize.AuthorizeConditionModel;
import jnpf.util.GeneraterSwapUtil;
import jnpf.database.model.superQuery.SuperQueryJsonModel;
import jnpf.database.model.superQuery.ConditionJsonModel;
import jnpf.database.model.superQuery.SuperQueryConditionModel;

import java.lang.reflect.Field;

import com.baomidou.mybatisplus.annotation.TableField;

import java.util.regex.Pattern;

import jnpf.model.QueryModel;

import java.util.stream.Collectors;

import jnpf.base.model.ColumnDataModel;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jnpf.database.model.superQuery.SuperJsonModel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import java.text.SimpleDateFormat;

import jnpf.util.*;

import java.util.*;

import jnpf.base.UserInfo;
import jnpf.permission.entity.UserEntity;

/**
 * knowMange
 * 版本： V3.5
 * 版权： 引迈信息技术有限公司（https://www.jnpfsoft.com）
 * 作者： JNPF开发平台组
 * 日期： 2025-05-19
 */
@Service
public class KnowMangeServiceImpl extends ServiceImpl<KnowMangeMapper, KnowMangeEntity> implements KnowMangeService {
    @Autowired
    private GeneraterSwapUtil generaterSwapUtil;

    @Autowired
    private UserProvider userProvider;

    @Autowired
    private FileMangeService fileMangeService;
    @Autowired
    private KnowMangeService knowMangeService;

    @Autowired
    private RagFlowKnowService ragFlowKnowService;

    @Autowired
    private DifyKnowService difyKnowService;

    @Override
    public List<KnowMangeEntity> getList(KnowMangePagination knowMangePagination) {
        return getTypeList(knowMangePagination, knowMangePagination.getDataType());
    }

    /**
     * 列表查询
     */
    @Override
    public List<KnowMangeEntity> getTypeList(KnowMangePagination knowMangePagination, String dataType) {
        String userId = userProvider.get().getUserId();
        List<String> AllIdList = new ArrayList();
        List<List<String>> intersectionList = new ArrayList<>();
        boolean isPc = ServletUtil.getHeader("jnpf-origin").equals("pc");
        String columnData = !isPc ? KnowMangeConstant.getAppColumnData() : KnowMangeConstant.getColumnData();
        ColumnDataModel columnDataModel = JsonUtil.getJsonToBean(columnData, ColumnDataModel.class);
        String ruleJson = !isPc ? JsonUtil.getObjectToString(columnDataModel.getRuleListApp()) : JsonUtil.getObjectToString(columnDataModel.getRuleList());

        int total = 0;
        int knowMangeNum = 0;
        QueryWrapper<KnowMangeEntity> knowMangeQueryWrapper = new QueryWrapper<>();
        int fileMangeNum = 0;
        QueryWrapper<FileMangeEntity> fileMangeQueryWrapper = new QueryWrapper<>();
        long fileMangecount = fileMangeService.count();
        List<String> allSuperIDlist = new ArrayList<>();
        String superOp = "";
        if (ObjectUtil.isNotEmpty(knowMangePagination.getSuperQueryJson())) {
            List<String> allSuperList = new ArrayList<>();
            List<List<String>> intersectionSuperList = new ArrayList<>();
            String queryJson = knowMangePagination.getSuperQueryJson();
            SuperJsonModel superJsonModel = JsonUtil.getJsonToBean(queryJson, SuperJsonModel.class);
            int superNum = 0;
            QueryWrapper<KnowMangeEntity> knowMangeSuperWrapper = new QueryWrapper<>();
            knowMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(knowMangeSuperWrapper, KnowMangeEntity.class, queryJson, "0"));
            int knowMangeNum1 = knowMangeSuperWrapper.getExpression().getNormal().size();
            if (knowMangeNum1 > 0) {
                List<String> knowMangeList = this.list(knowMangeSuperWrapper).stream().map(KnowMangeEntity::getId).collect(Collectors.toList());
                allSuperList.addAll(knowMangeList);
                intersectionSuperList.add(knowMangeList);
                superNum++;
            }
            String fileMangeTable = "file_mange";
            boolean fileMangeHasSql = queryJson.contains(fileMangeTable);
            List<String> fileMangeList = generaterSwapUtil.selectIdsByChildCondition(KnowMangeConstant.getTableList(), fileMangeTable, queryJson, null);
            if (fileMangeHasSql) {
                allSuperList.addAll(fileMangeList);
                intersectionSuperList.add(fileMangeList);
                superNum++;
            }
            superOp = superNum > 0 ? superJsonModel.getMatchLogic() : "";
            //and or
            if (superOp.equalsIgnoreCase("and")) {
                allSuperIDlist = generaterSwapUtil.getIntersection(intersectionSuperList);
            } else {
                allSuperIDlist = allSuperList;
            }
        }
        List<String> allRuleIDlist = new ArrayList<>();
        String ruleOp = "";
        if (ObjectUtil.isNotEmpty(ruleJson)) {
            List<String> allRuleList = new ArrayList<>();
            List<List<String>> intersectionRuleList = new ArrayList<>();
            SuperJsonModel ruleJsonModel = JsonUtil.getJsonToBean(ruleJson, SuperJsonModel.class);
            int ruleNum = 0;
            QueryWrapper<KnowMangeEntity> knowMangeSuperWrapper = new QueryWrapper<>();
            knowMangeSuperWrapper = generaterSwapUtil.getCondition(new QueryModel(knowMangeSuperWrapper, KnowMangeEntity.class, ruleJson, "0"));
            int knowMangeNum1 = knowMangeSuperWrapper.getExpression().getNormal().size();
            if (knowMangeNum1 > 0) {
                List<String> knowMangeList = this.list(knowMangeSuperWrapper).stream().map(KnowMangeEntity::getId).collect(Collectors.toList());
                allRuleList.addAll(knowMangeList);
                intersectionRuleList.add(knowMangeList);
                ruleNum++;
            }
            String fileMangeTable = "file_mange";
            boolean fileMangeHasSql = ruleJson.contains(fileMangeTable);
            List<String> fileMangeList = generaterSwapUtil.selectIdsByChildCondition(KnowMangeConstant.getTableList(), fileMangeTable, ruleJson, null);
            if (fileMangeHasSql) {
                allRuleList.addAll(fileMangeList);
                intersectionRuleList.add(fileMangeList);
                ruleNum++;
            }
            ruleOp = ruleNum > 0 ? ruleJsonModel.getMatchLogic() : "";
            //and or
            if (ruleOp.equalsIgnoreCase("and")) {
                allRuleIDlist = generaterSwapUtil.getIntersection(intersectionRuleList);
            } else {
                allRuleIDlist = allRuleList;
            }
        }
        boolean pcPermission = false;
        boolean appPermission = false;
        if (isPc && pcPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object knowMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(knowMangeQueryWrapper, KnowMangeEntity.class, knowMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(knowMangeObj)) {
                    return new ArrayList<>();
                } else {
                    knowMangeQueryWrapper = (QueryWrapper<KnowMangeEntity>) knowMangeObj;
                    if (knowMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        knowMangeNum++;
                    }
                }
                Object fileMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(fileMangeQueryWrapper, FileMangeEntity.class, knowMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(fileMangeObj)) {
                    return new ArrayList<>();
                } else {
                    fileMangeQueryWrapper = (QueryWrapper<FileMangeEntity>) fileMangeObj;
                    if (fileMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        fileMangeNum++;
                    }
                }
            }
        }
        if (!isPc && appPermission) {
            if (!userProvider.get().getIsAdministrator()) {
                Object knowMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(knowMangeQueryWrapper, KnowMangeEntity.class, knowMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(knowMangeObj)) {
                    return new ArrayList<>();
                } else {
                    knowMangeQueryWrapper = (QueryWrapper<KnowMangeEntity>) knowMangeObj;
                    if (knowMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        knowMangeNum++;
                    }
                }


                Object fileMangeObj = generaterSwapUtil.getAuthorizeCondition(new QueryModel(fileMangeQueryWrapper, FileMangeEntity.class, knowMangePagination.getMenuId(), "0"));
                if (ObjectUtil.isEmpty(fileMangeObj)) {
                    return new ArrayList<>();
                } else {
                    fileMangeQueryWrapper = (QueryWrapper<FileMangeEntity>) fileMangeObj;
                    if (fileMangeQueryWrapper.getExpression().getNormal().size() > 0) {
                        fileMangeNum++;
                    }
                }


            }
        }
        if (isPc) {
            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_name())) {
                fileMangeNum++;

                String value = knowMangePagination.getTableField113_name() instanceof List ? JsonUtil.getObjectToString(knowMangePagination.getTableField113_name()) : String.valueOf(knowMangePagination.getTableField113_name());
                fileMangeQueryWrapper.lambda().like(FileMangeEntity::getName, value);

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_datasetid())) {
                fileMangeNum++;

                String value = knowMangePagination.getTableField113_datasetid() instanceof List ? JsonUtil.getObjectToString(knowMangePagination.getTableField113_datasetid()) : String.valueOf(knowMangePagination.getTableField113_datasetid());
                fileMangeQueryWrapper.lambda().like(FileMangeEntity::getDatasetid, value);

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_blocks())) {
                fileMangeNum++;

                List BlocksList = JsonUtil.getJsonToList(knowMangePagination.getTableField113_blocks(), String.class);
                for (int i = 0; i < BlocksList.size(); i++) {
                    String id = String.valueOf(BlocksList.get(i));
                    boolean idAll = StringUtil.isNotEmpty(id) && !id.equals("null");
                    if (idAll) {
                        BigDecimal b = new BigDecimal(id);
                        if (i == 0) {
                            fileMangeQueryWrapper.lambda().ge(FileMangeEntity::getBlocks, b);
                        } else {
                            fileMangeQueryWrapper.lambda().le(FileMangeEntity::getBlocks, b);
                        }
                    }
                }


            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_uptime())) {
                fileMangeNum++;

                List UptimeList = JsonUtil.getJsonToList(knowMangePagination.getTableField113_uptime(), String.class);
                Long fir = Long.valueOf(String.valueOf(UptimeList.get(0)));
                Long sec = Long.valueOf(String.valueOf(UptimeList.get(1)));

                fileMangeQueryWrapper.lambda().ge(FileMangeEntity::getUptime, new Date(fir)).le(FileMangeEntity::getUptime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_type())) {
                fileMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] type = JsonUtil.getJsonToBean(knowMangePagination.getTableField113_type(), String[][].class);
                    for (int i = 0; i < type.length; i++) {
                        if (type[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(type[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> type = JsonUtil.getJsonToList(knowMangePagination.getTableField113_type(), String.class);
                        if (type.size() > 0) {
                            idList.addAll(type);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowMangePagination.getTableField113_type()));
                    }
                }
                fileMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(FileMangeEntity::getType, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_status())) {
                fileMangeNum++;

                List<String> idList = new ArrayList<>();
                try {
                    String[][] status = JsonUtil.getJsonToBean(knowMangePagination.getTableField113_status(), String[][].class);
                    for (int i = 0; i < status.length; i++) {
                        if (status[i].length > 0) {
                            idList.add(JsonUtil.getObjectToString(Arrays.asList(status[i])));
                        }
                    }
                } catch (Exception e1) {
                    try {
                        List<String> status = JsonUtil.getJsonToList(knowMangePagination.getTableField113_status(), String.class);
                        if (status.size() > 0) {
                            idList.addAll(status);
                        }
                    } catch (Exception e2) {
                        idList.add(String.valueOf(knowMangePagination.getTableField113_status()));
                    }
                }
                fileMangeQueryWrapper.lambda().and(t -> {
                    idList.forEach(tt -> {
                        t.like(FileMangeEntity::getStatus, tt).or();
                    });
                });

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getTableField113_ragfileid())) {
                fileMangeNum++;

                String value = knowMangePagination.getTableField113_ragfileid() instanceof List ? JsonUtil.getObjectToString(knowMangePagination.getTableField113_ragfileid()) : String.valueOf(knowMangePagination.getTableField113_ragfileid());
                fileMangeQueryWrapper.lambda().like(FileMangeEntity::getRagfileid, value);

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getName())) {
                knowMangeNum++;

                String value = knowMangePagination.getName() instanceof List ? JsonUtil.getObjectToString(knowMangePagination.getName()) : String.valueOf(knowMangePagination.getName());
                knowMangeQueryWrapper.lambda().like(KnowMangeEntity::getName, value);

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getDes())) {
                knowMangeNum++;

                String value = knowMangePagination.getDes() instanceof List ? JsonUtil.getObjectToString(knowMangePagination.getDes()) : String.valueOf(knowMangePagination.getDes());
                knowMangeQueryWrapper.lambda().like(KnowMangeEntity::getDes, value);

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getAmount())) {
                knowMangeNum++;

                List AmountList = JsonUtil.getJsonToList(knowMangePagination.getAmount(), String.class);
                for (int i = 0; i < AmountList.size(); i++) {
                    String id = String.valueOf(AmountList.get(i));
                    boolean idAll = StringUtil.isNotEmpty(id) && !id.equals("null");
                    if (idAll) {
                        BigDecimal b = new BigDecimal(id);
                        if (i == 0) {
                            knowMangeQueryWrapper.lambda().ge(KnowMangeEntity::getAmount, b);
                        } else {
                            knowMangeQueryWrapper.lambda().le(KnowMangeEntity::getAmount, b);
                        }
                    }
                }


            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getCreateuser())) {
                knowMangeNum++;

                knowMangeQueryWrapper.lambda().eq(KnowMangeEntity::getCreateuser, knowMangePagination.getCreateuser());

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getCreatetime())) {
                knowMangeNum++;

                List CreatetimeList = JsonUtil.getJsonToList(knowMangePagination.getCreatetime(), String.class);
                Long fir = Long.valueOf(String.valueOf(CreatetimeList.get(0)));
                Long sec = Long.valueOf(String.valueOf(CreatetimeList.get(1)));

                knowMangeQueryWrapper.lambda().ge(KnowMangeEntity::getCreatetime, new Date(fir)).le(KnowMangeEntity::getCreatetime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getUpdatetime())) {
                knowMangeNum++;

                List UpdatetimeList = JsonUtil.getJsonToList(knowMangePagination.getUpdatetime(), String.class);
                Long fir = Long.valueOf(String.valueOf(UpdatetimeList.get(0)));
                Long sec = Long.valueOf(String.valueOf(UpdatetimeList.get(1)));

                knowMangeQueryWrapper.lambda().ge(KnowMangeEntity::getUpdatetime, new Date(fir)).le(KnowMangeEntity::getUpdatetime, DateUtil.stringToDate(DateUtil.daFormatYmd(sec) + " 23:59:59"));


            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getUpdateuser())) {
                knowMangeNum++;

                knowMangeQueryWrapper.lambda().eq(KnowMangeEntity::getUpdateuser, knowMangePagination.getUpdateuser());

            }

            if (ObjectUtil.isNotEmpty(knowMangePagination.getDatasetid())) {
                knowMangeNum++;

                String value = knowMangePagination.getDatasetid() instanceof List ? JsonUtil.getObjectToString(knowMangePagination.getDatasetid()) : String.valueOf(knowMangePagination.getDatasetid());
                knowMangeQueryWrapper.lambda().like(KnowMangeEntity::getDatasetid, value);

            }

        }
        if (fileMangeNum > 0) {
            List<String> fileMangeIdList = fileMangeService.list(fileMangeQueryWrapper).stream().filter(t -> StringUtil.isNotEmpty(t.getKnowid())).map(t -> t.getKnowid()).collect(Collectors.toList());
            long count = fileMangeService.count();
            if (count > 0) {
                intersectionList.add(fileMangeIdList);
            }
            AllIdList.addAll(fileMangeIdList);
        }
        total += fileMangeNum;
        List<String> intersection = generaterSwapUtil.getIntersection(intersectionList);
        if (total > 0) {
            if (intersection.size() == 0) {
                intersection.add("jnpfNullList");
            }
            knowMangeQueryWrapper.lambda().in(KnowMangeEntity::getId, intersection);
        }
        //是否有高级查询
        if (StringUtil.isNotEmpty(superOp)) {
            if (allSuperIDlist.size() == 0) {
                allSuperIDlist.add("jnpfNullList");
            }
            List<String> finalAllSuperIDlist = allSuperIDlist;
            knowMangeQueryWrapper.lambda().and(t -> t.in(KnowMangeEntity::getId, finalAllSuperIDlist));
        }
        //是否有数据过滤查询
        if (StringUtil.isNotEmpty(ruleOp)) {
            if (allRuleIDlist.size() == 0) {
                allRuleIDlist.add("jnpfNullList");
            }
            List<String> finalAllRuleIDlist = allRuleIDlist;
            knowMangeQueryWrapper.lambda().and(t -> t.in(KnowMangeEntity::getId, finalAllRuleIDlist));
        }

        //排序
        if (StringUtil.isEmpty(knowMangePagination.getSidx())) {
            knowMangeQueryWrapper.lambda().orderByDesc(KnowMangeEntity::getId);
        } else {
            try {
                String sidx = knowMangePagination.getSidx();
                String[] strs = sidx.split("_name");
                KnowMangeEntity knowMangeEntity = new KnowMangeEntity();
                Field declaredField = knowMangeEntity.getClass().getDeclaredField(strs[0]);
                declaredField.setAccessible(true);
                String value = declaredField.getAnnotation(TableField.class).value();
                knowMangeQueryWrapper = "asc".equals(knowMangePagination.getSort().toLowerCase()) ? knowMangeQueryWrapper.orderByAsc(value) : knowMangeQueryWrapper.orderByDesc(value);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }

        if ("0".equals(dataType)) {
            if ((total > 0 && AllIdList.size() > 0) || total == 0) {
                Page<KnowMangeEntity> page = new Page<>(knowMangePagination.getCurrentPage(), knowMangePagination.getPageSize());
                IPage<KnowMangeEntity> userIPage = this.page(page, knowMangeQueryWrapper);
                return knowMangePagination.setData(userIPage.getRecords(), userIPage.getTotal());
            } else {
                List<KnowMangeEntity> list = new ArrayList();
                return knowMangePagination.setData(list, list.size());
            }
        } else {
            return this.list(knowMangeQueryWrapper);
        }
    }

    @Override
    public KnowMangeEntity getInfo(String id) {
        QueryWrapper<KnowMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(KnowMangeEntity::getId, id);
        return this.getOne(queryWrapper);
    }

    @Override
    public void create(KnowMangeEntity entity) {
        this.save(entity);
    }

    @Override
    public boolean update(String id, KnowMangeEntity entity) {
        return this.updateById(entity);
    }

    @Override
    public void delete(KnowMangeEntity entity) {
        if (entity != null) {
            this.removeById(entity.getId());
        }
    }

    /**
     * FileMange子表方法
     */
    @Override
    public List<FileMangeEntity> getFileMangeList(String id, KnowMangePagination knowMangePagination) {
        Map<String, Object> newtabMap = KnowMangeConstant.TABLEFIELDKEY.entrySet().stream().collect(Collectors.toMap(e -> e.getValue(), e -> e.getKey()));
        String tableName = "fileMange";
        tableName = newtabMap.get(tableName) == null ? tableName : newtabMap.get(tableName).toString();
        QueryWrapper<FileMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper = fileMangeService.getChild(knowMangePagination, queryWrapper);
        queryWrapper.lambda().eq(FileMangeEntity::getKnowid, id);
        generaterSwapUtil.wrapperHandle(KnowMangeConstant.getColumnData(), KnowMangeConstant.getAppColumnData(), queryWrapper, FileMangeEntity.class, "sub", tableName);
        return fileMangeService.list(queryWrapper);
    }

    /**
     * FileMange子表方法
     */
    @Override
    public List<FileMangeEntity> getFileMangeList(String id) {
        QueryWrapper<FileMangeEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(FileMangeEntity::getKnowid, id);
        return fileMangeService.list(queryWrapper);
    }

    /**
     * 验证表单唯一字段，正则，非空 i-0新增-1修改
     */
    @Override
    public String checkForm(KnowMangeForm form, int i) {
        boolean isUp = StringUtil.isNotEmpty(form.getId()) && !form.getId().equals("0");
        String id = "";
        String countRecover = "";
        if (isUp) {
            id = form.getId();
        }
        //主表字段验证
        if (StringUtil.isEmpty(form.getName())) {
            return "名称不能为空";
        }
        if (StringUtil.isNotEmpty(form.getName())) {
            form.setName(form.getName().trim());
            QueryWrapper<KnowMangeEntity> nameWrapper = new QueryWrapper<>();
            nameWrapper.lambda().eq(KnowMangeEntity::getName, form.getName());
            if (isUp) {
                nameWrapper.lambda().ne(KnowMangeEntity::getId, id);
            }
            if ((int) this.count(nameWrapper) > 0) {
                countRecover = "名称不能重复";
            }
        }
        //子表字段验证
        if (form.getFileMangeList() != null) {
        }
        return countRecover;
    }

    /**
     * 新增修改数据(事务回滚)
     *
     * @param id
     * @param knowMangeForm
     * @return
     */
    @Override
    @Transactional
    public KnowMangeEntity saveOrUpdate(KnowMangeForm knowMangeForm, String id, boolean isSave) {
        UserInfo userInfo = userProvider.get();
        UserEntity userEntity = generaterSwapUtil.getUser(userInfo.getUserId());
        knowMangeForm = JsonUtil.getJsonToBean(generaterSwapUtil.swapDatetime(KnowMangeConstant.getFormData(), knowMangeForm), KnowMangeForm.class);
        KnowMangeEntity entity = JsonUtil.getJsonToBean(knowMangeForm, KnowMangeEntity.class);

        if (isSave) {
            String mainId = RandomUtil.uuId();
            entity.setCreateuser(userInfo.getUserId());
            entity.setCreatetime(DateUtil.getNowDate());
            entity.setUpdatetime(null);
            entity.setUpdateuser(null);
            entity.setId(mainId);
        } else {
            entity.setCreateuser(userInfo.getUserId());
            entity.setCreatetime(DateUtil.getNowDate());
            entity.setUpdatetime(null);
            entity.setUpdateuser(null);
        }
        if (entity.getAmount() == null) {
            entity.setAmount(0);
        }
        this.saveOrUpdate(entity);

        //FileMange子表数据新增修改
        if (!isSave) {
            QueryWrapper<FileMangeEntity> FileMangequeryWrapper = new QueryWrapper<>();
            FileMangequeryWrapper.lambda().eq(FileMangeEntity::getKnowid, entity.getId());
            fileMangeService.remove(FileMangequeryWrapper);
        }
        if (knowMangeForm.getFileMangeList() != null) {
            List<FileMangeEntity> tableField113 = JsonUtil.getJsonToList(knowMangeForm.getFileMangeList(), FileMangeEntity.class);
            for (FileMangeEntity entitys : tableField113) {
                entitys.setId(RandomUtil.uuId());
                entitys.setKnowid(entity.getId());
                if (isSave) {
                } else {
                }
                fileMangeService.saveOrUpdate(entitys);
            }
        }
        //创建ragFlow知识库
        if(isSave){
            CreateKnowReq createDataSetsReq = ragFlowKnowService.getCreateKnowReq(knowMangeForm);
            RagFlowApiResult dataset = null;
            try {
                dataset = difyKnowService.createDataset(createDataSetsReq);
            } catch (Exception e) {
                throw new RagFlowException("RagFlow创建知识库失败");
            }
            if (dataset.getCode() == 0) {
                DatasetResp datasetResp = (DatasetResp) dataset.getData();
                knowMangeService.updateDatasetId(entity.getId(), datasetResp.getId());
            }
        }
        return entity;
    }

    @Override
    public void updateDatasetId(String id, String datasetId) {
        UpdateWrapper<KnowMangeEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("F_ID", id).set("datasetid", datasetId);
        this.update(updateWrapper);
    }

    @Override
    public List<KnowMangeEntity> getByIds(List<String> ids) {
        return this.baseMapper.selectBatchIds(ids);
    }

    @Override
    public void getSetAmount(String knowid) {
        if (StringUtil.isNotEmpty(knowid)) {
            // 统计当前知识库下的文件数量
            QueryWrapper<FileMangeEntity> countWrapper = new QueryWrapper<>();
            countWrapper.lambda().eq(FileMangeEntity::getKnowid, knowid);
            long fileCount = fileMangeService.count(countWrapper);

            // 更新know_mange表的amount字段
            KnowMangeEntity knowMange = knowMangeService.getById(knowid);
            if (knowMange != null) {
                knowMange.setAmount((int) fileCount);
                knowMangeService.updateById(knowMange);
            }
        }
    }
}
